#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if (lists.empty())return nullptr;
        ListNode* total = lists[0];
        for (int i = 1; i < lists.size(); i++) {
            ListNode* l1 = total;
            ListNode* l2 = lists[i];
            ListNode* dummp = new ListNode(0);
            ListNode* tail = dummp;
            while (l1 && l2) {
                if (l1->val < l2->val) {
                    tail->next = l1;
                    l1 = l1->next;
                }
                else {
                    tail->next = l2;
                    l2 = l2->next;
                }
                tail=tail->next;
            }
            tail->next = l1 ? l1 : l2;
            total=dummp->next;
        }
        return total;
    }
};
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if (lists.empty()) return nullptr;
        return mergeSort(lists, 0, lists.size() - 1);
    }
private:
    ListNode* mergeSort(vector<ListNode*>& lists, int left, int right) {
        if (left == right) return lists[left];
        if (left + 1 == right) return mergeTwoLists(lists[left], lists[right]);

        int mid = left + (right - left) / 2;
        ListNode* leftList = mergeSort(lists, left, mid);
        ListNode* rightList = mergeSort(lists, mid + 1, right);
        return mergeTwoLists(leftList, rightList);
    }
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode dummy(0);
        ListNode* tail = &dummy;

        while (l1 && l2) {
            if (l1->val < l2->val) {
                tail->next = l1;
                l1 = l1->next;
            }
            else {
                tail->next = l2;
                l2 = l2->next;
            }
            tail = tail->next;
        }
        tail->next = l1 ? l1 : l2;
        return dummy.next;
    }
};